package xyz.xiaomeiqiu.study.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;

import java.util.concurrent.atomic.AtomicBoolean;


public class SubOrder {
    Logger logger = LoggerFactory.getLogger(getClass());
    private JedisPool jedisPool;

    private AtomicBoolean running = new AtomicBoolean(false);
    private int timeout = 5000;
    private static long preOrderTime = 0;
    public SubOrder(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public void start() throws InterruptedException {
        Thread thread = new Thread(() -> {
            running.set(true);
            try (Jedis jedis = jedisPool.getResource()) {
                logger.info("开始订阅");
                jedis.subscribe(new JedisPubSub() {
                    @Override
                    public void onMessage(String channel, String message) {
                        // do somthing
                        logger.info("消费订单: channel{}, message:{}", channel, message);
                        if(message.equals("end")){
                            logger.info("活动结束: channel{}, message:{}", channel, message);
                            System.exit(0);
                        }
                    }
                }, "order-queue");
            }

        });
        thread.start();
    }

    public void stop(){
        running.set(false);
    }

}
